package com.example.batch.controller;

import com.example.batch.dto.BatchTaskAddDTO;
import com.example.batch.event.BatchTaskMetaEvent;
import com.example.batch.model.TMission;
import com.example.batch.dto.ProgressInfo;
import com.example.batch.service.TaskService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 1. 接收创建批量任务请求，封装成 BatchTaskMetaEvent，异步发送给 RocketMQ；
 * 2. 返回业务层生成的批次 ID。
 */
@Slf4j
@RestController
@RequestMapping("/batch")
@RequiredArgsConstructor
public class BatchTaskController {
    private final RocketMQTemplate rocketMQTemplate;
    private final RedisTemplate<String, Object> redisTemplate;
    private final TaskService taskService;

    @Autowired // 添加Spring自动注入注解
    private ObjectMapper objectMapper;


    @PostMapping("/tasks")
    public Map<String, Object> addBatchTasks(@RequestBody BatchTaskAddDTO requestDTO) {
        try {
            log.info("接收到批量任务请求，URL 数量={}，BatchName={}",
                    requestDTO.getUrls().size(), requestDTO.getName());

            // 生成全局唯一批次 ID
            String batchId = "BATCH_" + UUID.randomUUID().toString();

            // 构建事件
            BatchTaskMetaEvent event = BatchTaskMetaEvent.builder()
                    .batchId(batchId)
                    .name(requestDTO.getName())
                    .description(requestDTO.getDescription())
                    .urls(requestDTO.getUrls())
                    .taskParams(requestDTO.getTaskParams())
                    .action(requestDTO.getAction())
                    .build();


            log.info("构建的事件对象: {}", event);
            // 异步发送至 RocketMQ
            rocketMQTemplate.asyncSend("BATCH_TASK_TOPIC", objectMapper.writeValueAsString(event), new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("消息发送成功 offset={} msgId= {} ", sendResult.getQueueOffset(), sendResult.getMsgId());
                }

                @Override
                public void onException(Throwable e) {
                    log.error("消息发送失败 batchId={}", batchId, e);
                }
            });

            // 立即返回批次 ID 给客户端
            Map<String, Object> resp = new HashMap<>();
            resp.put("code", "200");
            resp.put("message", "SUCCESS");
            resp.put("data", batchId);
            return resp;
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败", e);
            Map<String, Object> resp = new HashMap<>();
            resp.put("code", "500");
            resp.put("message", "JSON序列化失败: " + e.getMessage());
            return resp;
        }
    }
}
